package com.aps.service.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aps.entity.domain.order.ApsOrder;
import com.aps.entity.domain.schedule.PriorityRule;
import com.aps.entity.eunm.ConsumerType;
import com.aps.entity.eunm.DishStatus;
import com.aps.service.IPriorityRuleService;
import com.aps.service.rep.PriorityRuleRep;

/**
 * @author liaoguangan
 * @description <优先级服务实现类>
 * @date 2018/4/2 9:59
 */
@Service
public class PriorityRuleServiceImpl implements IPriorityRuleService {

    @Autowired
    private PriorityRuleRep priorityRuleRep;

    /**
     * 按优先级排序
     *
     * @param apsOrders
     */
    @Override
    public void sort(List<ApsOrder> apsOrders) {

        //设置优先级
        for (ApsOrder order : apsOrders) {
            if (DishStatus.CHANGE.equals(order.getDishStatus())) { //退菜订单中的换菜
                order.setPriority(getPriority("PR1"));
            } else if (order.getUrgent() && ConsumerType.VIP.equals(order.getCstmrType())) { //加急VIP
                order.setPriority(getPriority("PR2"));
            } else if (DishStatus.ADD.equals(order.getDishStatus())) { //补菜
                order.setPriority(getPriority("PR3"));
            } else if (ConsumerType.VIP.equals(order.getCstmrType())) { //VIP
                order.setPriority(getPriority("PR4"));
            } else if (order.getIsAppt()) { //预定订单
                order.setPriority(getPriority("PR5"));
            } else { //普通订单
                order.setPriority(getPriority("PR6"));
            }
        }

        //排序
        Collections.sort(apsOrders, new Comparator<ApsOrder>() {

            @Override
            public int compare(ApsOrder o1, ApsOrder o2) {
                int temp = o1.getPriority() - o2.getPriority();
                return temp > 0 ? 1 : (temp == 0 ? 0 : -1);
            }
        });
    }

    private Integer getPriority(String priCode) {
        List<PriorityRule> rules = priorityRuleRep.findAll();
        for (PriorityRule pr : rules) {
            if (pr.getCode().equals(priCode)) {
                return pr.getPriority();
            }
        }
        return 1;
    }
}
